<?php
namespace Admin\Controller;

use Core\Constant;
use Core\Controller\AdminBaseController;
use Core\Exception\BusinessException;
use Core\Helper\CommonHelper;
use Core\Helper\MenuHelper;
use Core\Session\AdminSessionHelper;
use Exception;
use Logger;
use Zend\View\Model\JsonModel;
use Zend\View\Model\ViewModel;

/**
 * Created by JetBrains PhpStorm.
 * User: thanhnv
 * Date: 11/25/13
 * Time: 14:25 PM
 * To change this template use File | Settings | File Templates.
 */

class ArticleController extends AdminBaseController
{
    public function indexAction()
    {
        try{
            $categoryId = $this->params()->fromPost('category-id');

            $categoryTable = $this->getTableFinder()->getCategoryTable(AdminSessionHelper::getCurrentLang());
            $allCategory = $categoryTable->getAllCategoriesByGroupCode(Constant::$CATEGORY_GROUP_ARTICLE);
            $allSubCategory = $categoryTable->getAllCategoriesByGroupCode(Constant::$CATEGORY_GROUP_SUBARTICLE);

            $allArticleCategory = MenuHelper::getCategoryForCombo($allCategory);
            $allSubArticleCategory = MenuHelper::getCategoryForCombo($allSubCategory);

            $result = new ViewModel(array('categoryId' => $categoryId
            , 'allArticleCategory' => $allArticleCategory
            , 'allSubArticleCategory' => $allSubArticleCategory));

            return $result;
        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_ADMIN_EXCEPTION);
            return $this->genErrorView($e);
        }
    }

    public function listAction()
    {
        try{
            $categoryId = $this->params()->fromPost("category");
            $subCategoryId = $this->params()->fromPost("subCategory");
            $name = $this->params()->fromPost("name");

            $searchOption = array();
            $searchOption['categoryId'] = $categoryId;
            $searchOption['subCategoryId'] = $subCategoryId;
            $searchOption['header'] = $name;

            $sortData = $this->params()->fromPost("sort");
            if($sortData){
                $order = array();
                foreach ($sortData as $sortField) {
                    $field = $sortField['field'];
                    $direction = $sortField['dir'];
                    $orderClause = $field." ".$direction;
                    array_push($order, $orderClause);
                }
            }else{
                $order = array("created_date desc");
            }

            $page = $this->params()->fromPost("page");
            $rows = $this->params()->fromPost("pageSize");
            $offset = ($page - 1) * $rows;

            $articleTable = $this->getTableFinder()->getArticleTable();
            $result = $articleTable->searchArticle(true, $offset, $rows, $order, $searchOption);

            return new JsonModel(array(
                'rows' => $result['rows']->toArray(),
                'total' => $result['total'],
                'success'=>true,
            ));

        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_ADMIN_EXCEPTION);
            return $this->genJsonErrorView($e);
        }

    }

    function saveArticleAction(){
        try{
            $header = $this->params()->fromPost("header");
//            todo: add HtmlPurifier lib
//            $sumarize = Core_Tool_HtmlPurifier::purifyDefault($this->params()->fromPost('sumarize'));
            $sumarize = $this->params()->fromPost('sumarize');
            $content = $this->params()->fromPost("content");
            $thumbImage = $this->params()->fromPost("thumbImage");
            $topicImage = $this->params()->fromPost("topicImage");
            $primaryCategory = $this->params()->fromPost("primaryCategory");
            $subCategories = $this->params()->fromPost("subCategories");
            $alias = CommonHelper::vietnameseToASCII($header);
            $active = $this->params()->fromPost("active");
            $id = $this->params()->fromPost("id");

            $data =array("header"=>$header, "sumarize"=>$sumarize,
                "content"=>$content,"alias"=>$alias,'active'=>$active,
                "thumbnail"=>$thumbImage,"image"=>$topicImage);

            $articleTable = $this->getTableFinder()->getArticleTable();

            if($id) {
                $articleTable->update($data, $id);
                $articleItem = $articleTable->getArticle($id);
                $articleItem->detachAllCategory();
            }  else{
                $id = $articleTable->insert($data);
                $articleItem = $articleTable->getArticle($id);
            }

            if ($primaryCategory != null && $primaryCategory !=""){
                $articleItem->addCategory($primaryCategory);
            }

            if ($subCategories != null){
                foreach ($subCategories as $subCategoryId) {
                    $articleItem->addCategory($subCategoryId);
                }
            }

            return new JsonModel(array("success"=>true, "id"=>$id));
        }
        catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_ADMIN_EXCEPTION);
            return $this->genJsonErrorView($e);
        }
    }

    function getArticleForViewAction(){
        try{
            $id = $this->params()->fromPost("id");

            $articleService = $this->getTableFinder()->getArticleTable();
            $articleItem = $articleService->getArticle($id);
            $primaryCategoryItem = $articleItem->getPrimaryCategory();
            $subCategoryItems = $articleItem->getSubCategories();
            $allTags = $articleItem->getTags();
            $primaryCategoryStr = '';
            if($primaryCategoryItem)
                $primaryCategoryStr = $primaryCategoryItem->name;
            $subCategoryStr = '';
            foreach ($subCategoryItems as $aCategory) {
                $subCategoryStr = ', '.$aCategory->name.$subCategoryStr;
            }
            $subCategoryStr = substr($subCategoryStr, 1);
            $tagStr = '';
            if($allTags){
                foreach ($allTags as $aTag) {
                    $tagStr = ', '.$aTag->name.$tagStr;

                }
                $tagStr = substr($tagStr, 1);
            }

            return new JsonModel(array("success"=>true, "header"=>$articleItem->header,
                "sumarize"=>$articleItem->sumarize,
                "primary_category"=>':'.$primaryCategoryStr,
                "sub_category"=>':'.$subCategoryStr,
                "tag"=>':'.$tagStr));
        }
        catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_ADMIN_EXCEPTION);
            return $this->genJsonErrorView($e);
        }
    }

    public function addAction()
    {
        try{
            $result = new ViewModel(array());

            $articleId = $this->params()->fromQuery("id");
            if($articleId){
                $articleTable = $this->getTableFinder()->getArticleTable();
                $articleItem = $articleTable->getArticle($articleId);
                $result->setVariable("articleItem", $articleItem);
            }

            $categoryService = $this->getTableFinder()->getCategoryTable(AdminSessionHelper::getCurrentLang());
            $allCategory = $categoryService->getAllCategoriesByGroupCode(Constant::$CATEGORY_GROUP_ARTICLE);
            $allSubCategory = $categoryService->getAllCategoriesByGroupCode(Constant::$CATEGORY_GROUP_SUBARTICLE);

            $result->setVariable("allArticleCategory", MenuHelper::getCategoryForCombo($allCategory));
            $result->setVariable("allSubArticleCategory", MenuHelper::getCategoryForCombo($allSubCategory));

            return $result;
        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_ADMIN_EXCEPTION);
            return $this->genJsonErrorView($e);
        }
    }

    public function removeAction(){
        try{
            $id = $this->params()->fromPost("id");
            if(!$id){
                throw new BusinessException("Chưa truyền id để xóa ");
            }
            $articleTable = $this->getTableFinder()->getArticleTable();
            $articleTable->removeArticle($id );
            new JsonModel(array('success'=>true));
        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_ADMIN_EXCEPTION);
            return $this->genJsonErrorView($e);
        }
    }

}

